﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MSCacheSample.Infrastructure
{
    public class MemoryCachingInterceptor
        : IInterceptor
    {
        private ICachingProvider _cachingProvider;
        public MemoryCachingInterceptor(ICachingProvider cachingProvider)
        {
            _cachingProvider = cachingProvider;
        }
        public void Intercept(IInvocation invocation)
        {
            var target = invocation.MethodInvocationTarget ?? invocation.Method;
            var attr = target.GetCustomAttributes(typeof(MemoryCachingAttribute), false);
            if (attr == null || !attr.Any())
            {
                invocation.Proceed();
                return;
            }
            var cacheAttr = attr.First() as MemoryCachingAttribute;
            var className = invocation.TargetType.FullName;
            var methodName = target.Name;
            var expireTime = cacheAttr.ExpireTime;
            var arguments = invocation.Arguments;//Get method arguments.
            //var cacheKey = $"{className}_{methodName}_{expireTime}";
            var cacheKey = $"{className}_{methodName}";
            
            var val = _cachingProvider.Get(cacheKey);
            if (val==null)
            {
                invocation.Proceed();
                _cachingProvider.Set(cacheKey,invocation.ReturnValue,expireTime);
            }
            else
            {
                invocation.ReturnValue = val;
            }
        }
    }
}
